#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<limits.h>

typedef struct ListNode
{
    int val;
    struct ListNode *next;
}ListNode;
typedef struct 
{
    ListNode *top;
    int size;
}LinkedListStack;

/*构造函数*/
LinkedListStack *newLinkedListStack()
{
    LinkedListStack *s = (LinkedListStack *)malloc(sizeof(LinkedListStack));
    s->top = NULL;
    s->size = 0;
    return s;
}
/*析构函数*/
void delLinkedListStack(LinkedListStack *top)
{
    while (top->top)
    {
        ListNode *p = top->top;
        top->top = p->next;
        free(p);
    }   
    free(top);
}
/*获取栈的长度*/
int size(LinkedListStack *top)
{
    return top->size;
}
/*判断栈是否为空*/
bool isEmpty(LinkedListStack *top)
{
    return top->size==0;    
}
/*入栈*/
void push(LinkedListStack *s, int num)
{
    ListNode *p = (ListNode *)malloc(sizeof(ListNode));
    p->next = s->top;
    p->val = num;
    s->top = p;
    s->size++;    
}
/*访问栈顶*/
int peek(LinkedListStack *s)
{
    if (s->size == 0)
    {
        printf("栈为空\n");
        return INT_MAX;
    }
    return s->top->val;
}
/*出栈*/
int pop(LinkedListStack *top)
{
    int val = peek(top);
    ListNode *p = top->top;
    top->top = top->top->next;
    free(p);

    top->size--;
    return val;
}
/*打印栈*/
void print_stack(LinkedListStack *s)
{
    ListNode *cur = s->top;
    while (cur)
    {
        printf("%d>", cur->val);
        cur = cur->next;
    }
    printf("\n");
}

int main()
{   
    // 初始化栈1>3>2>5>4
    LinkedListStack *top = newLinkedListStack();
    push(top, 4);
    push(top, 5);
    push(top, 2);
    push(top, 3);
    push(top, 1);
    print_stack(top);

    // 输出栈顶
    printf("栈顶是:%d\n", peek(top));
    // 出栈
    pop(top);
    printf("栈顶是:%d\n", peek(top));

    // 析构
    delLinkedListStack(top);
    return 0;
}
